home
diamond Go Premium
Data Engineering Path  ·  PySpark

DataFrame Column Modification Operations

Manipulating DataFrame schemas in PySpark by adding, casting, renaming, or dropping columns.


What are the Schema Modification Operations?

A DataFrame is structurally immutable. In PySpark, we use structural DSL methods to generate a new DataFrame with modified schemas:

  • withColumn(colName, colExpression): Appends a new column or replaces an existing one if the name matches.
  • withColumnRenamed(oldName, newName): Alters the name of a specific column.
  • drop(colNames...): Excludes specific columns from the DataFrame projection.
  • cast(dataType): Changes the data type of an existing column.

Syntax and Common Scenarios

from pyspark.sql.functions import col
from pyspark.sql.types import IntegerType

# A. Add a column
df.withColumn("is_active", col("status") == "ACTIVE")

# B. Cast data type
df.withColumn("age", col("age").cast(IntegerType()))

# C. Rename column
df.withColumnRenamed("first_name", "first")

# D. Drop multiple columns
df.drop("address", "zip_code")

Example Usage Pipeline

Below is a complete, copy-paste-ready PySpark script demonstrating schema manipulations:

from pyspark.sql import SparkSession
from pyspark.sql.functions import col, when
from pyspark.sql.types import IntegerType

# 1. Setup local Spark session
spark = SparkSession.builder \
    .appName("DataFrame Schema Manipulations") \
    .master("local[*]") \
    .getOrCreate()

# 2. Dummy dataset with unclean inputs
data = [
    ("1001", "Alice", "92000", "ACTIVE"),
    ("1002", "Bob", "61000", "SUSPENDED"),
    ("1003", "Charlie", "48000", "ACTIVE"),
]
columns = ["id", "name", "raw_salary", "status"]
df = spark.createDataFrame(data, columns)

# 3. Clean and transform columns:
# - Rename 'name' to 'employee name'
# - Cast 'raw salary' to Integer and calculate net salary (bonus/tax)
# - Add conditional column 'eligible for bonus' based on active status
# - Drop the legacy 'raw salary' and 'status' columns
transformed_df = df \
    .withColumnRenamed("name", "employee_name") \
    .withColumn("salary", col("raw_salary").cast(IntegerType())) \
    .withColumn("net_income", col("salary") * 0.90) \
    .withColumn("bonus_eligible", when(col("status") == "ACTIVE", True).otherwise(False)) \
    .drop("raw_salary", "status")

# 4. Show results
print("=== Original Schema and Data ===")
df.show()
df.printSchema()

print("=== Transformed Schema and Data ===")
transformed_df.show()
transformed_df.printSchema()

Rendered Output:

=== Original Schema and Data ===
+----+-------+----------+---------+
|  id|   name|raw_salary|   status|
+----+-------+----------+---------+
|1001|  Alice|     92000|   ACTIVE|
|1002|    Bob|     61000|SUSPENDED|
|1003|Charlie|     48000|   ACTIVE|
+----+-------+----------+---------+

root
 |-- id: string (nullable = true)
 |-- name: string (nullable = true)
 |-- raw_salary: string (nullable = true)
 |-- status: string (nullable = true)

=== Transformed Schema and Data ===
+----+-------------+------+----------+--------------+
|  id|employee_name|salary|net_income|bonus_eligible|
+----+-------------+------+----------+--------------+
|1001|        Alice| 92000|   82800.0|          true|
|1002|          Bob| 61000|   54900.0|         false|
|1003|      Charlie| 48000|   43200.0|          true|
+----+-------------+------+----------+--------------+

root
 |-- id: string (nullable = true)
 |-- employee_name: string (nullable = true)
 |-- salary: integer (nullable = true)
 |-- net_income: double (nullable = true)
 |-- bonus_eligible: boolean (nullable = false)
Find this content helpful? ☕ Buy me a coffee

Entity Details

Create New Item

celebration
Enjoying the free content?

Create a free account to track your progress and save your place.

Create Free Account
help

Submit Technical Query

Have a question or run into an issue? Describe it below, upload an optional screenshot, and our engineering team will answer it!

image Attach image (optional)

Submit Feedback

build Free Developer Utility Free Tool
gavel

Privacy & Legal Disclaimer

1. Client-Side Browser Processing

All utility tools on DeepEngineerHub (including Image to PDF, Text Formatters, JSON Converters, and Encryptors) execute 100% locally within your client browser using WebAssembly and JavaScript. No uploaded images, text, or documents are transmitted, collected, or stored on remote servers.

2. Limitation of Liability ("As-Is" Provision)

Tools and services are provided free of charge for convenience and educational purposes "as-is" without warranties of any kind. DeepEngineerHub shall not be held liable for any data loss, formatting inconsistencies, or indirect damages resulting from tool usage.

3. Open Source & Third-Party Software

Certain utilities utilize open-source client libraries (such as jsPDF, Mermaid.js, Pyodide) licensed under MIT, Apache, or BSD open licenses. All intellectual property remains with their respective copyright holders.